import express from 'express';
import { addAnswer, goodAnswerReputation, queryAnswerBySubordinate, queryAnswerByUser } from '../service/answer.js';

const answerRouter = express.Router();

answerRouter.post('/answerQuestion', (req, res) => {
  let { answer_detail, answer_creator, subordinate_question } = req.body;

  if (!(typeof answer_detail === 'string' && answer_detail !== '' && answer_creator && subordinate_question)) {
    res.send({ resCode: 500, message: '绑定参数失败' });
  } else {
    const answerInfo = {
      ...req.body,
      create_time: new Date().toLocaleString(),
    };
    addAnswer(answerInfo);
    res.send({ resCode: 200, message: '感谢你提供的思路！' });
  }
});

answerRouter.get('/queryAnswerBySubordinate', async (req, res) => {
  const { subordinate_question } = req.query;
  if (!subordinate_question) {
    res.send({ resCode: 404, message: '找不到问题' });
  } else {
    const result = await queryAnswerBySubordinate(subordinate_question);

    res.send({ resCode: 200, data: result });
  }
});

answerRouter.get('/queryAnswerByUser', (req, res) => {
  const { user_id } = req.query;
  if (user_id) {
    queryAnswerByUser(user_id).then((data) => {
      if (data.length > 0) {
        res.send({ resCode: 200, data });
      } else {
        res.send({ resCode: 404, message: '用户没有回答' });
      }
    });
  }
});

answerRouter.post('/answerReputationUp', (req, res) => {
  const { body: data } = req;
  goodAnswerReputation(data.answerId, 1).then(() => {
    res.send({ resCode: 200, message: '点赞成功' });
  });
});

export default answerRouter;
